package com.veer.shop.service.impl.admin;

import java.util.concurrent.TimeUnit;

import com.veer.shop.service.impl.front.CustomerServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.veer.shop.config.Constants;
import com.veer.shop.config.OpResult;
import com.veer.shop.pojo.CurrentCustomerInfo;
import com.veer.shop.pojo.Token;
import com.veer.shop.repository.CustomerRepository;
import com.veer.shop.result.CustomerBaseResult;
import com.veer.shop.service.admin.CustomerLoginService;
import com.veer.shop.utils.RedisUtil;
/**
 * 手机验证码登录业务实现类
 * 
 * @author WangBin
 * 2021年1月4日-下午5:37:06
 */
@Component("PHONE_VCODE")
public class PhoneVCodeLoginServiceImpl implements CustomerLoginService{
	
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private CustomerRepository customerRepository;
	@Autowired
	private CustomerServiceImpl customerServiceImpl;
	@Autowired
	private ObjectMapper jackJsonMapper;
	
	/**
	 * 手机号 + 验证码 获取token
	 * 
	 * @param phone 手机号
	 * @param vcode 验证码
	 * @return opResult
	 */
	@Override
	public OpResult<Token> login(String phone, String vcode) {
		OpResult<Token> opResult = new OpResult<Token>();
		try {
			// 根据手机号去缓存中获取验证码
			String vcodeInRedis = redisUtil.get(Constants.REDIS_SUFFIX_PHONE_VCODE + phone);
			if(StringUtils.isEmpty(vcodeInRedis) || !vcodeInRedis.equals(vcode)) {
				throw new Exception("验证码错误");
			}
			// 根据手机号查询客户
			CustomerBaseResult customerBaseResult = customerRepository.getCustomerByPhone(phone);
			if(customerBaseResult == null) {
				throw new Exception("会员不存在");
			}
			// 获取会员token
			Token token = customerServiceImpl.getCustomerToken(customerBaseResult.getCustomerId(), Constants.JWT_PASSOWRD_SECRET);
			// 会员信息存入缓存
			CurrentCustomerInfo currentCustomerInfo = new CurrentCustomerInfo();
			currentCustomerInfo.setCustomerId(customerBaseResult.getCustomerId());
			currentCustomerInfo.setCustomerBn(customerBaseResult.getCustomerBn());
			currentCustomerInfo.setNickname(customerBaseResult.getNickname());
			currentCustomerInfo.setRealname(customerBaseResult.getRealname());
			currentCustomerInfo.setEmail(customerBaseResult.getEmail());
			currentCustomerInfo.setPhone(customerBaseResult.getPhone());
			String customerJsonStr = "";
			try {
				customerJsonStr = jackJsonMapper.writeValueAsString(currentCustomerInfo);
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
			redisUtil.setEx(token.getToken(), customerJsonStr, Constants.JWT_TOKEN_LIFE_TIME - 5 * 1000, TimeUnit.MILLISECONDS);
			// 返回值
			opResult.setData(token);
			opResult.setFlag(true);
		} catch (Exception e) {
			opResult.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return opResult;
	}
}
